package com.jshongli.myapplication.inspect;

import android.app.ProgressDialog;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.jshongli.myapplication.MainActivity;
import com.jshongli.myapplication.R;
import com.jshongli.myapplication.base.BaseActivity;
import com.jshongli.myapplication.common.adapter.PhotoPickerAdapter;
import com.jshongli.myapplication.common.callback.MyCallback;
import com.jshongli.myapplication.common.callback.UpdateCallback;
import com.jshongli.myapplication.common.utils.AccountManager;
import com.jshongli.myapplication.common.utils.AppManager;
import com.jshongli.myapplication.common.utils.SuccessDialogUtils;
import com.jshongli.myapplication.common.utils.ToastUtils;
import com.jshongli.myapplication.common.utils.URLUtils;
import com.jshongli.myapplication.common.utils.UtilPreferences;
import com.jshongli.myapplication.model.base.Update;
import com.jshongli.myapplication.model.inspect.PointBean;
import com.jshongli.myapplication.model.pic.PicUp;
import com.jshongli.myapplication.model.pic.PicUpload;
import com.jshongli.myapplication.model.user.UserInfo;
import com.yanzhenjie.album.Action;
import com.yanzhenjie.album.Album;
import com.yanzhenjie.album.AlbumFile;
import com.yanzhenjie.album.api.widget.Widget;
import com.yanzhenjie.album.impl.OnItemClickListener;
import com.zhy.http.okhttp.OkHttpUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;

public class SignCreateActivity extends BaseActivity {

    private ArrayAdapter<String> point_adapter;
    List<PointBean.DATA> point_List = new ArrayList<>();
    List<String> PointArray = new ArrayList ();
    private String selectpoint = "";

    @BindView(R.id.recy_pics)
    RecyclerView recy_pics;

    @BindView(R.id.spinner)
    Spinner spinner;

    @BindView(R.id.tv_zjd)
    TextView tv_zjd;

    String pId;
    String jd, wd;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_sign_create;
    }

    @Override
    protected void initData() {
        super.initData();

        pId = getIntent().getStringExtra("pId");
        jd = getIntent().getStringExtra("jd");
        wd = getIntent().getStringExtra("wd");

        tv_zjd.setText(getIntent().getStringExtra("Cable"));

        //获取点位
        getPoint();
    }

    @Override
    protected void initView() {
        super.initView();

        mToolbar.setTitle("签到");
        initToolbarBack(mToolbar);

        initPhotoPicker();
    }

    //region 初始化图片控件
    private PhotoPickerAdapter mPhotoPickerAdapter;
    private ArrayList<AlbumFile> mAlbumFiles1 = new ArrayList<>();

    private void initPhotoPicker() {

        recy_pics.setLayoutManager(new GridLayoutManager(this, 3) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        mPhotoPickerAdapter = new PhotoPickerAdapter(this, mAlbumFiles1, 1, new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                previewImage(mAlbumFiles1, position);
            }
        });
        recy_pics.setAdapter(mPhotoPickerAdapter);
    }

    private void previewImage(ArrayList<AlbumFile> albums, int position) {
        if (albums == null || albums.size() == 0) {
            Toast.makeText(this, "请选择图片", Toast.LENGTH_LONG).show();
        } else {
            if (albums.get(position) != null) {
                if (albums.get(position).getPath() != null && albums.get(position).getPath().startsWith("http://")) {
                    ArrayList<String> imageList = new ArrayList<>();
                    imageList.add(albums.get(position).getPath());
                    Album.gallery(mContext)
                            .requestCode(2)
                            .checkedList(imageList)
                            .checkable(false)
                            .widget(
                                    Widget.newDarkBuilder(this)
                                            .title("预览")
                                            .build()
                            )
                            .onResult(new Action<ArrayList<String>>() {
                                @Override
                                public void onAction(int requestCode, @NonNull ArrayList<String> result) {
                                    // TODO If it is optional, here you can accept the results of user selection.
                                }
                            })
                            .start();
                } else {
                    Album.galleryAlbum(this)
                            .checkable(false)
                            .checkedList(albums)
                            .currentPosition(position)
                            .widget(
                                    Widget.newDarkBuilder(this)
                                            .title("预览")
                                            .build()
                            )
                            .onResult(new Action<ArrayList<AlbumFile>>() {
                                @Override
                                public void onAction(int requestCode, @NonNull ArrayList<AlbumFile> result) {
                                }
                            })
                            .start();
                }
            }

        }
    }
    //endregion

    //region 更新图片
    @Override
    protected void onResume() {
        super.onResume();
        mAlbumFiles1 = (ArrayList<AlbumFile>) mPhotoPickerAdapter.getData();
    }
    //endregion

    //region HTTP post-- 照片上传
    List<PicUp> picUpAlreadyList = new ArrayList<>();
    List<PicUp> picUploadList = new ArrayList<>();

    private void uploadPics() {

        picUploadList.clear();
        for (AlbumFile path : mAlbumFiles1) {
            File originPic = new File(path.getPath());

            picUploadList.add(new PicUp(originPic, null));
        }

        if (picUploadList != null && !picUploadList.isEmpty()) {
            uploadPic(0);
        } else {
            addEvent();
        }

    }

    private void uploadPic(final int num) {
        pd.setMessage("正在上传第" + (num + 1) + "张图片," + getString(R.string.waiting));
        pd.show();

        final PicUp picUp = picUploadList.get(num);
        File pic = picUp.originFile;
        String fileId = null;
        String picName = null;
        boolean isUploaded = false;

        if (pic.getName() != null) {
            for (PicUp picup : picUpAlreadyList) {
                if (picup.originFile.getPath() != null && picup.originFile.getPath().equals(pic.getPath())) {
                    fileId = picup.fileId;
                    picUp.setFilePath(fileId);
                    isUploaded = true;
                    break;
                }
            }
            if (isUploaded) {
                if (picUploadList.size() - 1 == num) {
                    addEvent();
                } else if (picUploadList.size() - 1 > num) {
                    uploadPic(num + 1);
                }
                return;
            }
        }


        Log.d("TAG", "uploadPic: 正在上传第" + (num + 1) + "张图片");

        picName = pic.getName();
        Log.d("TAG", picName);
        String url = URLUtils.URLNoToken("manageAPI/file/upload");
        final File finalPic = pic;
        OkHttpUtils
                .post()
                .addFile("file", picName, pic)
                .url(url)
                .addHeader("Authorization", AccountManager.getToken())
                .tag(this)
                .build()
                .execute(new UpdateCallback<PicUpload>(mContext) {

                    @Override
                    public void onSuccess(PicUpload response) {
                        pd.dismiss();
                        String relative = response.data.filePath;
                        picUp.setFilePath(relative);
                        picUpAlreadyList.add(new PicUp(picUp.originFile, finalPic, relative));
                        if (picUploadList.size() - 1 == num) {
                            addEvent();
                        } else if (picUploadList.size() - 1 > num) {
                            uploadPic(num + 1);
                        }
                    }

                    @Override
                    public void onUpdating() {

                    }

                    @Override
                    public void onUpdateFailed() {
                        pd.dismiss();
//                        isStart = false;
                        ToastUtils.show(mContext, "第" + (num + 1) + "张图片上传失败,请重试");
                    }
                });

    }
    //endregion

    private ProgressDialog pd;

    private void getPoint()
    {
        pd = new ProgressDialog(this);
        pd.setCanceledOnTouchOutside(false);
        pd.setCancelable(false);
        pd.setMessage("正在加载...");
        pd.show();
        Map<String, String> map = new HashMap<>();
        OkHttpUtils.get().url(URLUtils.URLNoToken("manageAPI/bizPoint/getList")).addHeader("Authorization", AccountManager.getToken()).params(map).tag(this)
                .build().execute(new MyCallback<PointBean>(mContext) {


            @Override
            public void onSuccess(PointBean response) {
                pd.dismiss();
                if(response.success)
                {
                    point_List.clear();
                    point_List.addAll(response.data);

                    for(PointBean.DATA item:point_List)
                    {
                        PointArray.add(item.pileNum+"-"+item.address);
                    }
                    if(PointArray.size()>0)
                    {
                        PointBean.DATA item = point_List.get(0);
                        selectpoint = String.valueOf(item.id);
                    }

                    //适配器
                    point_adapter = new ArrayAdapter<String>(mContext, android.R.layout.simple_spinner_item, PointArray);
                    //设置样式
                    point_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    //加载适配器
                    spinner.setAdapter(point_adapter);
                    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                        @Override
                        public void onItemSelected(AdapterView<?> parent, View view,
                                                   int position, long id) {
//                            String str = parent.getItemAtPosition(position).toString();
                            PointBean.DATA item = point_List.get(position);
                            selectpoint = String.valueOf(item.id);
                        }

                        @Override
                        public void onNothingSelected(AdapterView<?> parent) {
                            // TODO Auto-generated method stub
                        }
                    });


                }else {
                    ToastUtils.show(mContext, "数据解析出错");
                }
            }

            @Override
            public void onFail(PointBean response) {
                super.onFail(response);
                ToastUtils.show(mContext, "获取点位失败，请重新进入");
            }
        });

    }

    //region HTTP -- 上传签到
    SuccessDialogUtils tipDialog;

    public void addEvent() {
        pd.dismiss();

        if(selectpoint.isEmpty())
        {
            ToastUtils.show(mContext, "无法获取签到点位");
            return;
        }

        String url = URLUtils.URLNoToken("manageAPI/bizClickin/add");

        Map<String, String> map = new HashMap<String, String>();
        map.put("patrolId", pId);//
        map.put("pointId", selectpoint);//
        map.put("lonLat", jd+","+wd);
        StringBuffer IMGURL = new StringBuffer();
        if (picUploadList != null && !picUploadList.isEmpty()) {
            for (int i = 0; i < picUploadList.size(); i++) {
                if (picUploadList.get(i) != null) {
                    if (i == 0) {
                        IMGURL.append(picUploadList.get(i).fileId);
                    } else {
                        IMGURL.append("," + picUploadList.get(i).fileId);
                    }
                }
            }
        }
        String imgurl = IMGURL.toString();


        if (imgurl != null && imgurl.length() != 0) {
            map.put("picPath", imgurl);
        }

        Gson gson = new Gson();
        final String s = gson.toJson(map);

        OkHttpUtils
                .postString()
                .url(url)
                .addHeader("Authorization", AccountManager.getToken())
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(s)
                .build()
                .execute(new UpdateCallback<Update>(mContext) {

                    @Override
                    public void onSuccess(Update response) {

                        tipDialog = new SuccessDialogUtils(mActivity, R.style.loading_dialog, "上传成功", R.mipmap.ic_right, true);
                        tipDialog.show();
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                tipDialog.dismiss();
                                finish();
                            }
                        }, 1000);
                    }

                    @Override
                    public void onUpdating() {

                    }

                    @Override
                    public void onUpdateFailed() {
                        tipDialog = new SuccessDialogUtils(mActivity, R.style.loading_dialog, "签到失败，请勿重复签到", R.mipmap.ic_error, true);
                        tipDialog.show();
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                tipDialog.dismiss();
                            }
                        }, 1000);
                    }
                });
    }

    @OnClick({ R.id.tv_submit})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_submit:

                uploadPics();
                break;

        }
    }
}